import { useState, useCallback, useEffect } from "react";
import { message } from "antd";
import { type Comment } from '@/types/content/comment'
import { queryCommentById, removeCommentById } from "@/api/content/comment";
import { useParams } from "react-router-dom";

export const useCommentList = () => {
    const { id } = useParams()
    const [messageApi] = message.useMessage();
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState<Pagination>({
        pageNo: 1,
        pageSize: 10,
        total: 0,
    });
    const [tableData, setTableData] = useState<Comment[]>([]);
    /**
     * 获取评论列表
     */
    const getCommentList = useCallback(async () => {
        if (!id) return
        setLoading(true);
        const params = {
            articleId: id,
            pageNo: pagination.pageNo,
            pageSize: pagination.pageSize,

        };
        const res = await queryCommentById(params);
        setLoading(false);
        if (res.code === 200) {
            setTableData(res.data.rows || []);
            setPagination({
                pageNo: pagination.pageNo,
                pageSize: pagination.pageSize,
                total: res.data.total,
            });
        }
    }, [id, pagination.pageNo, pagination.pageSize]);

    /**
   * 删除评论
   * @param id 
   */
    const removeComment = async (row: Comment) => {
        setLoading(true)
        const res = await removeCommentById(row.id)
        setLoading(false)
        if (res.code === 200) {
            messageApi.success('删除成功')
            if (tableData.length === 1) {
                setPagination({
                    pageNo: Math.max(1, pagination.pageNo - 1),
                    pageSize: pagination.pageSize,
                    total: pagination.total
                })
            } else {
                getCommentList()
            }
        }
    }
    useEffect(() => {
        getCommentList();
    }, [getCommentList]);
    return {
        setPagination,
        pagination,
        tableData,
        removeComment,
        loading
    }
}